package com.tpshion.cloud.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.tpshion.cloud.auth.domain.dto.*;
import com.tpshion.cloud.auth.domain.entity.Role;
import com.tpshion.cloud.auth.domain.entity.RolePermission;
import com.tpshion.cloud.auth.mapper.RoleMapper;
import com.tpshion.cloud.auth.mapper.RolePermissionMapper;
import com.tpshion.cloud.auth.service.RoleService;
import com.tpshion.cloud.auth.utils.support.MenuData;
import com.tpshion.cloud.common.support.Assert;
import com.tpshion.cloud.common.support.ErrorCode;
import com.tpshion.cloud.common.support.Result;
import com.tpshion.cloud.common.utils.IdUtil;
import com.tpshion.cloud.core.annotation.Permission;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 角色管理模块
 */
@RestController
public class RoleController {

    private static final Logger log = LoggerFactory.getLogger(RoleController.class);

    @Autowired
    private RoleService roleService;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    /**
     * 分页查询角色
     */
    @PostMapping("/role")
    public Result<?> getPageRoles(@RequestBody @Validated QueryRoleDto queryRoleDto){
        log.info("*** getPageRoles queryRoleDto:{}",queryRoleDto);
        PageInfo pageRoles = roleService.getPageRoles(queryRoleDto);
        log.info("*** pageRoles:{}",pageRoles);
        return Result.ok(pageRoles);
    }

    /**
     * 查询角色是否已存在
     */
    @PostMapping("/checkRole")
    public Result<?> checkRole(@RequestBody CheckRoleDto checkRoleDto){
        log.info("*** checkRole checkRoleDto:{}",checkRoleDto);
        if(StringUtils.isEmpty(checkRoleDto.getRoleId()) && StringUtils.isEmpty(checkRoleDto.getRoleName())){
            return Result.fail("角色id和角色名称不能同时为空");
        }
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(checkRoleDto.getRoleId())){
            queryWrapper.eq("id", checkRoleDto.getRoleId());
        }
        if(!StringUtils.isEmpty(checkRoleDto.getRoleName())){
            queryWrapper.eq("role_name", checkRoleDto.getRoleName());
        }
        Integer count = roleMapper.selectCount(queryWrapper);
        if(count > 0){
            return Result.fail("角色已存在");
        }
        return Result.ok();
    }

    /**
     * 添加角色
     */
    @PostMapping(value = "/role",params = {"action=add"})
    @Permission("role:add")
    public Result<?> addRole(@RequestBody @Validated AddRoleDto addRoleDto){
        Role role = new Role();
        role.setId(IdUtil.getUUID());
        role.setRoleName(addRoleDto.getRoleName());
        role.setNote(addRoleDto.getNote());
        role.setCreateTime(LocalDateTime.now());
        roleMapper.insert(role);
        return Result.ok(role);
    }

    /**
     * 修改角色信息
     */
    @PostMapping(value = "/role",params = {"action=upd"})
    @Permission("role:update")
    public Result<?> updateRole(@RequestBody @Validated UpdateRoleDto updateRoleDto){
        updateRoleDto.init();
        Role role = roleMapper.selectById(updateRoleDto.getRoleId());
        Assert.notNull(role, ErrorCode.ROLE_NOT_EXIST);
        role.setRoleName(updateRoleDto.getRoleName());
        role.setNote(updateRoleDto.getNote());
        role.setUpdateTime(LocalDateTime.now());
        roleMapper.updateById(role);
        return Result.ok(role);
    }

    /**
     * 删除角色
     */
    @PostMapping(value = "/role",params = {"action=del"})
    @Permission("role:delete")
    public Result<?> deleteRole(@RequestParam("roleId") String roleId){
        roleService.deleteRole(roleId);
        return Result.ok();
    }

    /**
     * 为角色分配菜单权限，提供数据
     */
    @PostMapping(value = "/role/menu")
    public Result<?> getRoleMenuData(@RequestParam("roleId") String roleId){
        List<MenuData> list = roleService.getRoleMenuData(roleId);
        log.info("*** getRoleMenuData list:{}",list);
        return Result.ok(list);
    }

    /**
     * 分配角色菜单权限
     */
    @PostMapping(value = "/role/menu",params = {"action=auth"})
    @Permission("role-menu:auth")
    public Result<?> setRoleMenuData(@RequestBody @Validated SetRoleMenuDto setRoleMenuDto){
        log.info("*** setRoleMenuDto:{}", setRoleMenuDto);
        roleService.setRoleMenuData(setRoleMenuDto);
        return Result.ok();
    }

    /**
     * 查询角色拥有的功能权限id列表
     */
    @PostMapping(value = "/role/permissions")
    public Result<?> getRolePermissions(@RequestParam("roleId") String roleId){
        List<String> ids = rolePermissionMapper.getPermissionIds(roleId);
        return Result.ok(ids);
    }

    /**
     * 分配角色功能权限
     */
    @PostMapping(value = "/role/permissions", params = {"action=auth"})
    @Permission("role-auth:auth")
    public Result<?> addRolePermissions(@RequestBody @Validated SetRolePermissionDto setRolePermissionDto){
        roleService.setRolePermission(setRolePermissionDto);
        return Result.ok();
    }
}
